package com.healthySys.backend.config.security.filter;

import com.healthySys.backend.config.security.db.DBUSerConfigManager;
import com.healthySys.common.utils.JWTStoreUtil;
import com.healthySys.common.utils.ResponseUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * 验证Token, 将用户姓名放入 redis 安全上下文容器
 */
@Slf4j
@Component
public class JWTFilter extends OncePerRequestFilter {

    @Resource
    private JWTStoreUtil jwtStoreUtil;
    @Resource
    private DBUSerConfigManager dbUserConfigManager;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 1. 提取Token
        String authorization = request.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            //filterChain.doFilter(request, response); 放行更下一个过滤器
            ResponseUtils.writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, 40101, "未提供Token，请先登录");
            return;
        }

        String token = authorization.substring(7);

        // 2. 验证Token有效性
        if (!JWTStoreUtil.validateJWT(token)) {
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
            ResponseUtils.writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, 40102, "Token无效或已过期");

            return;
        }

        // 3. 解析Token
        Claims claims = JWTStoreUtil.parseJWT(token);
        String username = claims.getSubject();

        log.info("获取到用户{}", username);

        // 4. 验证Token是否在存储中 解决用户被抢占登录
        if (!jwtStoreUtil.validateStoredJWT(username, token)) {
            //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token已失效");
            ResponseUtils.writeJsonResponse(response,HttpServletResponse.SC_UNAUTHORIZED, 40103, "Token已失效（已经退出或已在其他设备登录）");
            return;
        }

        // 5. 创建认证对象
        UserDetails userDetails = dbUserConfigManager.loadUserByUsername(username);
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities())
        );
        log.info("当前用户角色/权限{}",userDetails.getAuthorities());

        // 6. 继续过滤器链
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return Objects.equals("/sys/login", request.getRequestURI());
    }
}
